const db = wx.cloud.database();
const direction = db.collection('directions')
const app = getApp();
Page({
  data: {
    directions: []
  },
  onClickLeft() {
    wx.navigateBack({
      delta: 1,
    })
  },
  async onLoad(options) {
    let res = await direction.get();
    let directions = res.data.map(v => {
      return v.name
    })
    let user = app.globalData.user;
    let choosen = user.choosen
    if (choosen.length == 0) {
      choosen = directions
    }
    user.choosen = choosen
    this.setData({
      directions,
      user: app.globalData.user
    })
  },

  change(e) {
    let choosen = this.data.user.choosen
    let picked = this.data.directions[Number(e.detail.value)]
    let found = choosen.indexOf(picked);
    if (found <= e.currentTarget.dataset.id) {
      wx.vibrateShort({
        type: 'ligth',
      })
      let errMsg = `第${found + 1}志愿已经选${picked}`
      wx.showToast({
        title: errMsg,
      })
      return
    } else {
      choosen.splice(e.currentTarget.dataset.id, 0, picked)
      choosen.splice(choosen.lastIndexOf(picked), 1)
    }
    let user = this.data.user;
    user.choosen = choosen
    this.setData({
      user
    })
  },
  async post() {
    let res = await wx.cloud.callFunction({
      name: 'pic_post',
      data: {
        user: this.data.user
      }
    })

    if (res.result.res.errMsg.indexOf('ok') > -1) {
      wx.showToast({
        title: '提交成功',
      })
      wx.navigateTo({
        url: '/pages/appLetWork/work19/list',
      })
    }

  }
})